<template>
	<view class="chat-container">

<!-- 
		<view>inputMessage:{{inputMessage }}
			textResult:{{textResult}}</view> -->
		<!-- 聊天内容区域 -->
		<scroll-view class="chat-messages" scroll-y="true" scroll-with-animation>
			
			<view v-for="(item, index) in messages" :key="index" class="message-item" :class="item.role">
				<view class="message-content">
					<text>{{item.content}}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 输入框区域 -->
		<view class="input-area">
			<!-- 		<img class="videosimg" src="http://localhost:9999/videos/vedio.png" > -->
			<view class="videosimg" @touchstart="startRecord"> 🎤</view>
			<input class="input-box" v-model="inputMessage" placeholder="请输入您的问题..." />
			<!-- <input 
			  :value="inputMessage" 
			  @input="inputMessage = $event.target.value"    @confirm="sendMessage"
			  placeholder="输入消息" 
			/> -->
			<button class="send-btn" @click="sendMessage">发送</button>
		</view>
		
		<vieww class="toast">

		</vieww>
		<!-- 		<view class="container">
			<view class="sound-wave">
				<view class="wave-bar" v-for="(item, index) in bars" :key="index" :style="{
        height: `${item.height}px`,
        animationDelay: `${item.delay}s`
      }"></view>
			</view>
		</view> -->
		<!-- 录音遮罩层 -->
		<view class="voice-mask" v-show="isshow">
			<view class="voice-timer">{{formattedTime}}</view>
			<view class="voice-wave">
				<view class="time-box">
					<span class="start-taste-line">
						<hr class="hr1 hr" />
						<hr class="hr2 hr" />
						<hr class="hr3 hr" />
						<hr class="hr4 hr" />
						<hr class="hr5 hr" />
						<hr class="hr6 hr" />
						<hr class="hr7 hr" />
						<hr class="hr8 hr" />
						<hr class="hr9 hr" />
						<hr class="hr10 hr" />
					</span>
				</view>

			</view>
			<view class="voice-controls">
				<view class="control-btn cancel" @click="gettext">
					<uni-icons type="closeempty" size="28" color="#FFFFFF"></uni-icons>
				</view>
				<!-- 		<view class="control-btn record">
					
					<view class="record-inner"></view>
				</view> -->
				<button class="control-btn text"@touchend="stopRecord" >文</button>
			</view>
			<view class="voice-indicator">
				<uni-icons type="mic-filled" size="24" color="#FFFFFF"></uni-icons>
				<view class="indicator-line"></view>
			</view>
		</view>
	</view>

</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
	} from 'vue'
	let timeInterval = ""
	let time = ref(0)
	const bars = [{
			height: 10,
			delay: 0.1
		},
		{
			height: 30,
			delay: 0.2
		},
		{
			height: 50,
			delay: 0.3
		},
		{
			height: 30,
			delay: 0.4
		},
		{
			height: 10,
			delay: 0.5
		},
		{
			height: 30,
			delay: 0.6
		},
		{
			height: 50,
			delay: 0.7
		},
		{
			height: 30,
			delay: 0.8
		}
	]
	// 插件调用
	// const plugin = requirePlugin('WechatSI')
	// const manager = plugin.getRecordRecognitionManager()
	const inputMessage = ref('')
	const messages = ref([{
		role: 'assistant',
		content: '您好！我是蜗牛AI助手，有什么可以帮您的吗？'
	}])

	const isRecording = ref(true);
	const imageUrl = 'https://ai-public.mastergo.com/ai/img_res/adeeb65c978ccd56542b948664138e66.jpg';
	const decorationUrl = 'https://ai-public.mastergo.com/ai/img_res/b7811e3856bc099bddd37d78b7d9a6c4.jpg';

	const textResult = ref('')
	const isshow = ref(false)

	onMounted(() => {
		 console.log('组件挂载完成，inputMessage 初始值:', inputMessage.value)
		manager.onRecognize = (res) => {
			console.log('中间结果：', res.result)
			// 可选：实时显示中间识别结果
			// textResult.value = res.result
		}

		manager.onStop = (res) => {
			// 获取最终翻译结果  inputMessage textResult
			console.log('最终结果：', res.result)
			if (res.result) {
				inputMessage.value = res.result
				textResult.value = res.result
			} else {
				textResult.value = '未识别到语音，请重试'
			}
		}

		manager.onError = (err) => {
			console.error('识别出错', err)
			textResult.value = '识别出错，请重试'
			isRecording.value = false
		}
	})
	// 格式化时间为 MM:SS
	const formattedTime = computed(() => {
		const mins = Math.floor(time.value / 60)
		const secs = time.value % 60
		return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
	})

	function startRedio() {
		isshow.value = true
	}

	function gettext() {
		isshow.value = false;
		clearInterval(timeInterval);
		// inputMessage.value =  textResult.value;
	}
	const startRecord = () => {
		isshow.value = true;
		textResult.value = '';
		timeInterval = setInterval(() => {
			time.value++
		}, 1000)
		manager.start({
			lang: 'zh_CN'
		})
	}

	const stopRecord = () => {
		time.value = 0;
		// formattedTime="";
		isshow.value = false;
		manager.stop(); // 停止
		clearInterval(timeInterval);
	}
	const sendMessage = async () => {
		console.log('按钮点击触发，输入内容:', inputMessage.value)
		if (!inputMessage.value.trim()) return

		// 添加用户消息
		messages.value.push({
			role: 'user',
			content: inputMessage.value
		})

		const userMessage = inputMessage.value
		inputMessage.value = '' // 清空输入框

		try {
			// 发送请求到后端 messages,
			const res = await uni.request({
				url: 'http://127.0.0.1:8081/ai/chat',
				method: 'POST',
				data: messages, //带历史会话的方式
				// {
				// 	message: userMessage
				// },
				header: {
					'Content-Type': 'application/json'
				}
			})

			// 添加AI回复
			messages.value.push({
				role: 'assistant',
				// content: res.data.response || '收到回复但内容为空'
				content: res.data || '收到回复但内容为空'
			})

		} catch (error) {
			console.error('请求出错:', error)
			messages.value.push({
				role: 'assistant',
				content: '抱歉，请求服务出错，请稍后再试'
			})
		}

		// 滚动到底部
		setTimeout(() => {
			uni.pageScrollTo({
				scrollTop: 99999,
				duration: 300
			})
		}, 100)
	}
	
	
</script>

<style>
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 10px;
		box-sizing: border-box;
	}

	.chat-header {
		text-align: center;
		padding: 15px 0;
		font-weight: bold;
		font-size: 18px;
		border-bottom: 1px solid #eee;
	}

	.videosimg {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.chat-messages {
		flex: 1;
		padding: 10px;
		overflow-y: auto;
	}

	.message-item {
		margin-bottom: 15px;
	}

	.message-item.user {
		display: flex;
		justify-content: flex-end;
	}

	.message-item.assistant {
		display: flex;
		justify-content: flex-start;
	}

	.message-content {
		max-width: 70%;
		padding: 10px 15px;
		border-radius: 5px;
		word-break: break-word;
	}

	.user .message-content {
		background-color: #95ec69;
		color: #000;
	}

	.assistant .message-content {
		background-color: #f0f0f0;
		color: #333;
	}

	.input-area {
		display: flex;
		padding: 10px;
		border-top: 1px solid #eee;
		background-color: #fff;
		align-items: center;
	}

	.input-box {
		flex: 1;
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 5px;
		margin-right: 10px;
	}

	.text :hover {
		background-color: #007AFF !important;
	}

	.send-btn {
		padding: 0 20px;
		background-color: #07c160;
		color: white;
		border-radius: 5px;
	}

	/* 语音遮罩 */
	.voice-mask {
		position: fixed;
		left: 0;
		right: 0;
		bottom: -47%;
		top: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.voice-timer {
		font-size: 40px;
		color: #FFFFFF;
		font-weight: 300;
		margin-bottom: 40rpx;
	}

	.voice-wave {
		width: 100rpx;
		text-align: center;
		height: 60rpx;
		background: linear-gradient(180deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%);
		border-radius: 30rpx;
		margin-bottom: 100rpx;
	}

	.voice-controls {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 100rpx;
	}

	.control-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100rpx;
		height: 100rpx;
		margin: 0 60rpx;
	}

	.cancel {
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
	}

	.record {
		width: 140rpx;
		height: 140rpx;
		background-color: #FFFFFF;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.record-inner {
		width: 100rpx;
		height: 100rpx;
		background-color: #007AFF;
		border-radius: 50%;
	}

	.text {
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		color: #FFFFFF;
		font-size: 16px;
	}

	.voice-indicator {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.indicator-line {
		width: 4rpx;
		height: 200rpx;
		background: linear-gradient(180deg, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%);
		margin-top: 20rpx;
	}

	/* //声波颜色 */
	.time-box .start-taste-line hr {
		background-color: red;
		width: 3px;
		height: 6px;
		margin: 0 0.03rem;
		display: inline-block;
		border: none;
	}

	.hr {
		animation: note 0.2s ease-in-out;
		animation-iteration-count: infinite;
		animation-direction: alternate;
	}

	.hr1 {
		animation-delay: -1s;
	}

	.hr2 {
		animation-delay: -0.9s;
	}

	.hr3 {
		animation-delay: -0.8s;
	}

	.hr4 {
		animation-delay: -0.7s;
	}

	.hr5 {
		animation-delay: -0.6s;
	}

	.hr6 {
		animation-delay: -0.5s;
	}

	.hr7 {
		animation-delay: -0.4s;
	}

	.hr8 {
		animation-delay: -0.3s;
	}

	.hr9 {
		animation-delay: -0.2s;
	}

	.hr10 {
		animation-delay: -0.1s;
	}

	@keyframes note {
		from {
			transform: scaleY(1);
		}

		to {
			transform: scaleY(4);
		}
	}
</style>